#include "Engine.h"
#include "Renderer/D3D10RenderDevice.h"
#include "Renderer/RenderSystem.h"
#include "Renderer/HardwareResourceManager.h"
#include "SceneManager.h"
#include "Utility/Utility.h"

static CEngine* g_pEngineInst = NULL;
CEngine* GetEngine()
{
	return g_pEngineInst;
}

void SetEngineInstance( CEngine* pEngine )
{
	g_pEngineInst = pEngine;
}

CEngine::CEngine()
{

}

CEngine::~CEngine()
{
	UnInit();
}

void CEngine::Init(HWND hMainWnd, int nViewWidth, int nViewHeight)
{
	_InitRenderDevice(hMainWnd, nViewWidth, nViewWidth);
	OnWindowResize(nViewWidth, nViewHeight);

	m_pRenderer = new CRenderSystem(m_pRenderDevice);
	m_pHWResMgr = new CHardwareResourceManager(m_pRenderDevice);
	m_pSceneMgr = new CSceneManager;

	m_pRenderer->Init();
}

void CEngine::UnInit()
{
	if (m_pRenderer)
		m_pRenderer->UnInit();

	if (m_pRenderDevice)
		m_pRenderDevice->UnInit();

	SAFE_DELETE(m_pSceneMgr);
	SAFE_DELETE(m_pHWResMgr);
	SAFE_DELETE(m_pRenderer);
	SAFE_DELETE(m_pRenderDevice);
}

void CEngine::Update( float fTime )
{
	m_pSceneMgr->Update(fTime);
}

void CEngine::Render()
{
	m_pSceneMgr->Render();
	m_pRenderer->BeginRender();
	m_pRenderer->DrawAll();
	m_pRenderer->EndRender();
}


CRenderSystem* CEngine::GetRenderer()
{
	return m_pRenderer;
}

CSceneManager* CEngine::GetSceneMgr()
{
	return m_pSceneMgr;
}

CHardwareResourceManager* CEngine::GetHwResMgr()
{
	return m_pHWResMgr;
}

CD3D10RenderDevice* CEngine::GetRenderDevice()
{
	return m_pRenderDevice;
}

void CEngine::_InitRenderDevice(HWND hMainWnd, int nViewWidth, int nViewHeight)
{
	m_pRenderDevice = new CD3D10RenderDevice;
	bool bRet = m_pRenderDevice->Init(hMainWnd, nViewWidth, nViewWidth);
	if (!bRet)
	{
		MessageBox(0, L"Init D3D10Device Failed", 0, 0);
		PostQuitMessage(0);
	}
}

void CEngine::OnWindowResize( int nViewWidth, int nViewHeight )
{
	m_nViewWidth  = nViewWidth;
	m_nViewHeight = nViewHeight;
	m_pRenderDevice->OnWindowResize(nViewWidth, nViewWidth);
}

void CEngine::OnResetDevice()
{

}

void CEngine::SwapBuffer()
{
	m_pRenderDevice->Present();

}


